package main

import (
	"fmt"
	"net"
	"sort"
	"sync"
)

func worker(ports chan int, wg *sync.WaitGroup, results chan int) {
	for p := range ports {
		address := fmt.Sprintf("180.101.49.193:%d", p)
		conn, err := net.Dial("tcp", address)
		if err != nil {
			fmt.Printf("error!! %d 链接失败\n", p)
			results <- 0
			continue
		}
		conn.Close()
		results <- p
		fmt.Printf("%d 端口打开了，，，，，\n", p)
		// fmt.Println(p)
		// wg.Done()
	}
}

func main() {
	ports := make(chan int, 100)
	results := make(chan int)
	var openports []int
	var closedports []int
	var wg sync.WaitGroup

	for i := 0; i < cap(ports); i++ {
		go worker(ports, &wg, results)
	}

	// for i := 1; i < 1024; i++ {
	// 	wg.Add(1)
	// 	ports <- i
	// }
	go func() {
		for i := 1; i < 1024; i++ {
			// wg.Add(1)
			ports <- i
		}
	}()

	for i := 1; i < 1024; i++ {
		port := <-results
		if port != 0 {
			openports = append(openports, port)
		} else {
			closedports = append(closedports, port)
		}
	}

	// wg.Wait()
	close(ports)
	close(results)

	sort.Ints(openports)
	sort.Ints(closedports)

	for _, port := range openports {
		fmt.Printf("%d open\n", port)
	}
}

// func main() {
// 	start := time.Now()
// 	var wg sync.WaitGroup
// 	for i := 21; i < 120; i++ {
// 		wg.Add(1)
// 		go func(j int) {
// 			defer wg.Done()
// 			address := fmt.Sprintf("20.194.168.28:%d", j)
// 			conn, err := net.Dial("tcp", address)
// 			if err != nil {
// 				fmt.Printf("%s 关闭了\n", address)
// 				return
// 			}
// 			conn.Close()
// 			fmt.Printf("%s 打开了，，，，\n", address)
// 		}(i)

// 	}
// 	wg.Wait()
// 	elapsed := time.Since(start) / 1e9
// 	fmt.Printf("\n\n %d seconds", elapsed)
// }

// func main() {
// 	for i := 21; i < 120; i++ {
// 		address := fmt.Sprintf("20.194.168.28:%d", i)
// 		conn, err := net.Dial("tcp", address)
// 		if err != nil {
// 			fmt.Printf("%s 关闭了\n", address)
// 			continue
// 		}
// 		conn.Close()
// 		fmt.Printf("%s 打开了，，，，\n", address)
// 	}
// }
